﻿namespace Pre.CRM.Controllers
{
    using System.Web.Mvc;

    using VIT.BusinessLogicLayer.CRM;
    using VIT.DataTransferObjects;
    using VIT.Library;
    using VIT.Library.Web;
    using Pre.CRM.Models;

    [Authorize]
    public class AgentController : Controller
    {
        private readonly AgentBLL _agentBLL;
        private readonly CustomerBLL _customerBLL;

        public AgentController()
        {
            this._agentBLL = new AgentBLL();
            this._customerBLL = new CustomerBLL();
        }

        public ActionResult Index()
        {
            var model = new CRMModel();
            model.Agents = this._agentBLL.GetAllDomainAgent();
            model.ThuNhap = this._customerBLL.Thunhap();
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(string domain)
        {
            domain = domain.Replace("http://", string.Empty);
            if (domain.EndsWith("/")) domain = domain.Substring(0, domain.Length - 1);

            var dto = new AgentConfigDto();
            try
            {
                var url = "http://" + domain + "/" + SettingsManager.Constants.JsonPage + "/GetConnection";

                var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
                {
                    token = Encrypt.EnCode(domain)
                });

                var httpResponse = (new URL()).PostJson(url, json);
                if (httpResponse != "{\"d\":null}")
                {
                    json = httpResponse.Replace("{\"d\":{\"__type\":\"VIT.DataTransferObjects.AgentConfigDto\",", "{").Replace("}}", "}");
                    dto = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<AgentConfigDto>(json);
                    dto.Id = dto.Id.DeEnCode(dto.FreeDay);

                    this._agentBLL.SaveAgent(dto, domain);
                }
            }
            catch {}

            var data = this._agentBLL.GetAllDomainAgent();
            return View(data);
        }

        public ActionResult Detail(string domain)
        {
            var data = this._agentBLL.GetAgentByDomain(domain);
            return View(data);
        }

        [HttpPost]
        public ActionResult Detail(AgentDto agent)
        {
            this._agentBLL.UpdateAgent(agent);
            return View(agent);
        }
    }
}
